<script setup lang="js">
import { reactive, ref, toRef, toRefs } from 'vue'

const refCount = ref({
  count0: 0,
  title0: 'ref',
})

const reactiveCount = reactive({
  count1: 0,
  title1: 'reactive',
})

const reactiveCount2 = reactive({
  count2: ref(2),
  title2: ref('reactive2'),
})

const { count1 } = toRefs(reactiveCount)
// toRefs()将对象的所有字段均转为响应式字段，解构出来的字段是Ref数据类型
// toRefs()要求被转换的对象是Reactive类型，不支持Ref类型
// 解构对象在脚本中使用.value访问
// toRefs()解构出来的对象进行值更新，也会同步更新原对象
// 原对象的字段值更新，会同步更新被toRefs()解构出来的对象的值
// 若不采用解构的方式，则需要通过.value.key的方式访问，key为对象的字段名称

const { count0 } = toRefs(refCount)
// 会报错，转换不成功，count0解构出来是undefined
// 可以使用toRefs(refCount.value)，refCount.value是一个Reactive对象

console.log('count1', count1, 'count0', count0)

const { count2, title2 } = reactiveCount2
// count2和title2解构出来不是Ref对象，是Ref对象对应的数据（基本变量）
console.log('count2', count2, 'title2', title2)

const toRefCount = toRef(reactiveCount, 'count1')
// toRef()将对象的指定字段转为响应式字段，其它字段保持不变
// toRef()采用非解构方式，变量名可以是其它名字（不用与字段一致）
</script>

<template>
  <div class="q-pa-6">
    <q-banner class="bg-purple-4 text-white text-center mb-8">
      <p class="text-h4">陈一非 23211860123</p>
    </q-banner>

    <div class="bg-white rounded-lg shadow p-4 mb-6">
      <h3 class="text-xl text-center font-bold mb-4">作业十一</h3>
      <div class="row justify-center gap-4">
        <q-btn @click="count1++" color="primary" rounded-full label="count1++" />
        <q-btn @click="count2++" color="secondary" rounded-full label="count2++" />
        <q-btn @click="refCount.count0++" color="accent" rounded-full label="refCount.count0++" />
        <q-btn @click="reactiveCount.count1++" color="positive" rounded-full label="reactiveCount.count1++" />
        <q-btn @click="reactiveCount2.count2++" color="negative" rounded-full label="reactiveCount2.count2++" />
        <q-btn @click="reactiveCount2.count2.value++" color="warning" rounded-full label="reactiveCount2.count2.value++" />
      </div>
    </div>

    <q-card class="q-ma-auto" style="max-width: 600px;">
      <q-card-section>
        <p class="text-lg mb-2"><strong>count0变量值：</strong>{{ count0 }}</p>
        <p class="text-lg mb-2"><strong>refCount变量值：</strong>{{ refCount }}</p>
        <p class="text-lg mb-2"><strong>count1变量值：</strong>{{ count1 }}</p>
        <p class="text-lg mb-2"><strong>toRefCount变量值：</strong>{{ toRefCount }}</p>
        <p class="text-lg mb-2"><strong>reactiveCount变量值：</strong>{{ reactiveCount }}</p>
        <p class="text-lg mb-2"><strong>count2变量值：</strong>{{ count2 }}</p>
        <p class="text-lg"><strong>reactiveCount2变量值：</strong>{{ reactiveCount2 }}</p>
      </q-card-section>
    </q-card>
  </div>
</template>

<style scoped>

</style>
